using System.Collections;
using System.Collections.Generic;
using Unity.Per.Common.UIFrameWork;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Unity.Per.Common.UIFrameWork
{
    public class BindPanel :BaseModuleMono, IPointerDownHandler
    {
        public RectTransform PanelRegion;
        public bool IsOpen = false;

        [SerializeField]
        private BasePanel basePanelPrefab;


        private BasePanel m_basePanelInstance;
        public BasePanel basePanelInstance {
            get {
                if ( basePanelPrefab == null )
                    return null;

                if ( m_basePanelInstance == null ) {
                    m_basePanelInstance = Instantiate<BasePanel>(basePanelPrefab);
                    m_basePanelInstance.bindPanel = this;

                    if ( PanelRegion ) {
                        m_basePanelInstance.transform.SetParent(PanelRegion,false);
                    }
                }

                return m_basePanelInstance;
            }
        }

        [SerializeField]
        private BasePanelSlot m_basePanelSlot;
        public BasePanelSlot basePanelSlot {
            get {
                if ( m_basePanelSlot == null ) {
                    UpdateBasePanelSlot(GetComponentInParent<BasePanelSlot>());
                }
                return m_basePanelSlot;
            }
            set {
                UpdateBasePanelSlot(value);
            }
        }

        void UpdateBasePanelSlot(BasePanelSlot basePanelSlot) {
            if ( basePanelSlot == m_basePanelSlot )
                return;

            if ( m_basePanelSlot ) {
                m_basePanelSlot.RemoveModule(this);
                m_basePanelSlot.RemoveBindPanel(this);
            }

            m_basePanelSlot = basePanelSlot;

            if ( m_basePanelSlot ) {
                m_basePanelSlot.AddModule(this);
                m_basePanelSlot.AddBindPanel(this);
            }
        }


        protected override void OnModuleInit() {
            base.OnModuleInit();
            if ( basePanelSlot == null ) {
                Debug.Log("Error No BasePanelSlot");
                return;
            }
        }

        protected override void OnModuleStart() {
            base.OnModuleStart();
            if ( basePanelSlot && basePanelInstance ) {
                basePanelInstance.ModuleStart();
            }
        }

        protected override void OnModuleStop() {
            base.OnModuleStop();
            if ( basePanelSlot && basePanelInstance ) {
                basePanelInstance.ModuleStop();
            }
        }


        public void OnPointerDown(PointerEventData eventData) {
            if ( basePanelSlot == null )
                return;

            if ( basePanelSlot.CurrentBindPanel == this ) {
                //basePanelSlot.Close();
            } else {
                basePanelSlot.Open(this);
            }
        }

    }
}